package com.open.cloud.rbac.service.application.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.open.cloud.rbac.entity.application.CoreApplication;
import com.open.cloud.rbac.entity.application.CoreApplicationInterface;
import com.open.cloud.rbac.entity.application.CoreApplicationModule;
import com.open.cloud.rbac.mapper.application.CoreApplicationInterfaceMapper;
import com.open.cloud.rbac.mapper.application.CoreApplicationMapper;
import com.open.cloud.rbac.mapper.application.CoreApplicationModuleMapper;
import com.open.cloud.rbac.object.application.CoreApplicationDto;
import com.open.cloud.rbac.object.application.CoreApplicationSelectDto;
import com.open.cloud.rbac.object.application.CoreApplicationSyncDto;
import com.open.cloud.rbac.service.application.ICoreApplicationService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 系统应用表 服务实现类
 * </p>
 *
 * @author wangzengzhou01
 * @since 2024-12-23
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CoreApplicationServiceImpl extends ServiceImpl<CoreApplicationMapper, CoreApplication>
        implements ICoreApplicationService {

//    @Resource
//    private CoreApplicationMapper applicationMapper;

    @Resource
    private CoreApplicationModuleMapper applicationModuleMapper;

    @Resource
    private CoreApplicationInterfaceMapper applicationInterfaceMapper;

    @Resource
    private Snowflake snowflake;

    /**
     * 新增应用
     *
     * @param applicationDto
     * @return
     */
    @Override
    public JSONObject addApplicationInfo(CoreApplicationDto applicationDto) {
        CoreApplication application = new CoreApplication();
        BeanUtils.copyProperties(applicationDto, application);
        application.setId(snowflake.nextIdStr());
        application.setCreateTime(new Date());
        application.setUpdateTime(new Date());

        int i = this.baseMapper.insert(application);
        JSONObject resultObj = new JSONObject();
        if (i > 0) {
            resultObj.put("code", 200);
            resultObj.put("message", "创建成功");
        } else {
            resultObj.put("code", 500);
            resultObj.put("message", "创建失败");
        }
        return resultObj;
    }

    /**
     * 编辑应用
     *
     * @param applicationDto
     * @return
     */
    @Override
    public JSONObject updateApplicationInfo(CoreApplicationDto applicationDto) {
        CoreApplication application = new CoreApplication();
        BeanUtils.copyProperties(applicationDto, application);
        application.setUpdateTime(new Date());
        int i = this.baseMapper.updateById(application);
        JSONObject resultObj = new JSONObject();
        if (i > 0) {
            resultObj.put("code", 200);
            resultObj.put("message", "修改成功");
        } else {
            resultObj.put("code", 500);
            resultObj.put("message", "修改失败");
        }
        return resultObj;
    }

    /**
     * 删除应用
     *
     * @param applicationId
     * @return
     */
    @Override
    public JSONObject deleteApplicationById(String applicationId) {
        int i = this.baseMapper.deleteById(applicationId);
        JSONObject resultObj = new JSONObject();
        if (i > 0) {
            resultObj.put("code", 200);
            resultObj.put("message", "删除成功");
        } else {
            resultObj.put("code", 500);
            resultObj.put("message", "删除失败");
        }
        return resultObj;
    }

    /**
     * 分页查询应用
     *
     * @param applicationSelectDto
     * @return
     */
    @Override
    public IPage<CoreApplication> selectApplicationByPage(CoreApplicationSelectDto applicationSelectDto) {
        LambdaQueryWrapper<CoreApplication> queryWrapper = Wrappers.<CoreApplication>lambdaQuery();
//                .like(ObjectUtils.isNotEmpty(applicationSelectDto.get))
        IPage<CoreApplication> page = new Page<>(applicationSelectDto.getPageNo(), applicationSelectDto.getPageSize());
        IPage<CoreApplication> data = this.baseMapper.selectPage(page, queryWrapper);
        return data;
    }

    /**
     * 同步应用接口
     *
     * @param applicationSyncDto
     * @return
     */
    @Override
    public JSONObject syncAppInterface(CoreApplicationSyncDto applicationSyncDto) {
        String syncUrl = applicationSyncDto.getInterfaceSyncUrl();
        String applicationName = applicationSyncDto.getApplicationName();
        String applicationId = applicationSyncDto.getApplicationId();
        HttpResponse response = HttpRequest.get(syncUrl)
                .header("Content-Type", "application/json")
                .execute();
        String body = response.body();
        JSONArray resultArr = JSONObject.parseArray(body);

        List<CoreApplicationInterface> interfaceList = new ArrayList<>();
        List<CoreApplicationModule> moduleList = new ArrayList<>();

        resultArr.forEach(obj -> {
            JSONObject item = (JSONObject) obj;
            String moduleName = item.getString("moduleName");
            String requestServer = item.getString("requestServer");
            if (requestServer.equals(applicationName)) {
                CoreApplicationInterface applicationInterface = new CoreApplicationInterface();
                applicationInterface.setId(snowflake.nextIdStr());
                applicationInterface.setApplicationId(applicationId);
                applicationInterface.setRequestServer(requestServer);
                applicationInterface.setModuleName(moduleName);
                applicationInterface.setRequestName(item.getString("requestName"));
                applicationInterface.setRequestType(item.getString("requestType"));
                applicationInterface.setRequestUrl(item.getString("requestUrl"));
                applicationInterface.setRemark(item.getString("remark"));
                applicationInterface.setCreateTime(new Date());
                applicationInterface.setUpdateTime(new Date());
                String uniqueUrl = item.getString("requestServer") + item.get("requestUrl");
                applicationInterface.setUniqueUrl(uniqueUrl);
                Object entityInfo = item.get("entityInfo");
                if (ObjectUtils.isNotEmpty(entityInfo)) {
                    applicationInterface.setResultInfo(JSONObject.toJSONString(entityInfo));
                }
                interfaceList.add(applicationInterface);

                CoreApplicationModule applicationModule = new CoreApplicationModule();
                applicationModule.setId(snowflake.nextIdStr());
                applicationModule.setApplicationId(applicationId);
                applicationModule.setModuleName(moduleName);
                applicationModule.setRequestServer(requestServer);
                applicationModule.setModuleUrl(item.getString("moduleUrl"));
                String uniqueModuleUrl = item.getString("requestServer") + item.get("moduleUrl");
                applicationModule.setUniqueUrl(uniqueModuleUrl);
                applicationModule.setCreateTime(new Date());
                applicationModule.setUpdateTime(new Date());
                moduleList.add(applicationModule);
            }
        });

        applicationModuleMapper.batchInsertModuleInterface(moduleList);
        applicationInterfaceMapper.batchInsertAppInterface(interfaceList);

        JSONObject resultObj = new JSONObject();
        resultObj.put("code", 200);
        resultObj.put("message", "同步成功");
        return resultObj;
    }

    /**
     * 根据应用名称删除接口
     *
     * @param application
     * @return
     */
    @Override
    public Integer deleteApiInterfaceByApplication(String application) {
        applicationModuleMapper.deleteInterfaceByRequestServer(application);
        Integer serverNum = applicationInterfaceMapper.deleteInterfaceByRequestServer(application);
        return serverNum;
    }

    /**
     * 获取应用列表
     *
     * @return
     */
    @Override
    public List<CoreApplication> getApplicationList(CoreApplicationSelectDto appSelectDto) {
        LambdaQueryWrapper<CoreApplication> queryWrapper = Wrappers.<CoreApplication>lambdaQuery();
        List<CoreApplication> data = this.baseMapper.selectList(queryWrapper);
        return data;
    }


}
